package com.wangsd.system.service;

import com.gitee.fastmybatis.core.query.Query;
import com.gitee.fastmybatis.core.query.Sort;
import com.wangsd.common.exception.BusinessErrorEnum;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.common.utils.StringUtils;
import com.wangsd.system.entity.SysMenu;
import com.wangsd.system.entity.SysUser;
import com.wangsd.system.entity.SysUserRole;
import com.wangsd.system.mapper.SysUserMapper;
import com.wangsd.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户Service业务层处理
 *
 * @author wsd
 * @date 2021-03-16
 */
@Service
public class SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysMenuService menuService;
    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * 查询用户
     *
     * @param id 用户ID
     * @return 用户
     */
    public SysUser selectSysUserById(Long id) {
        return sysUserMapper.getById(id);
    }

    /**
     * 查询用户列表
     *
     * @param sysUser 用户
     * @return 用户
     */
    public List<SysUser> selectSysUserList(SysUser sysUser, String loginCode) {
        Query query = new Query();
        if (sysUser.getUserType() != null) {
            query.eq("user_type", sysUser.getUserType());
        }
        query.likeRight("parent_code", loginCode);
        if (StringUtils.isNotEmpty(sysUser.getParentCode())) {
            query.likeRight("parent_code", sysUser.getParentCode());
        }
        if (StringUtils.isNotEmpty(sysUser.getUsername())) {
            query.like("username", sysUser.getUsername());
        }
        query.orderby("id", Sort.DESC);
        List<SysUser> list = sysUserMapper.list(query);
        return list;
    }

    /**
     * 新增用户
     *
     * @param sysUser 用户
     * @return 结果
     */
    @Transactional
    public void insertSysUser(SysUser sysUser) {
        sysUserMapper.saveIgnoreNull(sysUser);
        saveUserRole(sysUser);
    }

    /**
     * 修改用户
     *
     * @param sysUser 用户
     * @return 结果
     */
    @Transactional
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateIgnoreNull(sysUser);
        saveUserRole(sysUser);
    }

    /**
     * 保存用户和角色关系
     *
     * @param sysUser
     */
    private void saveUserRole(SysUser sysUser) {
        if (sysUser.getRoleIds() != null && sysUser.getRoleIds().size() > 0) {
            userRoleMapper.deleteByQuery(new Query().eq("user_id", sysUser.getId()));
            List<SysUserRole> list = new ArrayList<>();
            for (Long roleId : sysUser.getRoleIds()) {
                SysUserRole userRole = new SysUserRole();
                userRole.setRole_id(roleId);
                userRole.setUser_id(sysUser.getId());
                list.add(userRole);
            }
            userRoleMapper.saveBatch(list);
        }
    }

    /**
     * 删除用户信息
     *
     * @param id 用户ID
     * @return 结果
     */
    @Transactional
    public int deleteSysUserById(Long id) {
        userRoleMapper.deleteByQuery(new Query().eq("user_id", id));
        return sysUserMapper.deleteById(id);
    }

    /**
     * 根据登陆名称查询用户
     *
     * @param username
     * @return
     */
    public SysUser selectByUsername(String username) {
        return sysUserMapper.getByColumn("username", username);
    }

    /**
     * 判断名称是否重复
     *
     * @param name
     * @param id
     */
    public SysUser checkName(String name, Long id) {
        Query query = new Query();
        query.eq("username", name);
        if (id != null) {
            query.notEq("id", id);
        }
        SysUser sysUser = sysUserMapper.getByQuery(query);
        return sysUser;
    }

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    public SysUser userLogin(String username, String password) {
        Query query = new Query();
        query.eq("username", username);
        query.eq("password", password);
        SysUser user = sysUserMapper.getByQuery(query);
        if (user == null) {
            throw new BusinessException(BusinessErrorEnum.USER_ACCOUNT_OR_PASSWORD_ERROR);
        }
        if (!user.getStatus()) {
            throw new BusinessException(BusinessErrorEnum.USER_DISABLE);
        }
        return user;
    }

    /**
     * 获取登录用户权限
     *
     * @param sysUser
     * @return
     */
    public SysUser selectPermission(SysUser sysUser) {
        List<SysMenu> menuList;
        if (sysUser.getId() == 1) {//超级管理员
            menuList = menuService.selectSysMenuByUserId(null);
        } else {
            menuList = menuService.selectSysMenuByUserId(sysUser.getId());
        }
        List<String> keySing = menuList.stream().map(SysMenu::getKeySign).collect(Collectors.toList());
        sysUser.setMenuList(menuList);
        sysUser.setPermissionList(keySing);
        return sysUser;
    }

    /**
     * 启用 禁用
     *
     * @param id
     */
    public void changeStatus(Long id) {
        SysUser entity = this.selectSysUserById(id);
        entity.setStatus(!entity.getStatus());
        sysUserMapper.updateIgnoreNull(entity);
    }
}
